<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/13
 * Time: 21:23
 */

class Goods_model extends CI_Model
{

    public $limit_rows = 15;

    public $style_setting = [
        1 => '网红INS风',
//        2 => '测试',
//        3 => '测试2',
//        4 => '测试4',
//        5 => '测试5',
    ];

    public function __construct()
    {
        parent::__construct();
        $this->table_name = 'goods';
    }

    public function goods_id($shopify_id = 0, $param = array())
    {
        $this->db->from('goods');
        if ($shopify_id) {
			$this->db->where('shopify_id', $shopify_id);
		}

		if ($param) {
			$this->db->where($param);
		}


        $query = $this->db->get();
        $goods_info = $query->row_array();

        return $goods_info['goods_id'];
    }

    public function goods_sn_max($admin_id)
    {
        $query = $this->db->from('goods')->select('*')->where('admin_id', $admin_id)->order_by('goods_id desc')->get();

        $info = $query->row_array();

        $query = $this->db->from('admin')->where('admin_id', $admin_id)->get();

        $admin = $query->row_array();

        if ($info) {

            return $admin['ab_name'] . sprintf("%04d", ltrim(preg_replace("/[A-Za-z]+/", '', $info['goods_sn']), '0') + 1);
        } else {
            return $admin['ab_name'] . '0001';
        }
    }
    
    public function sales_goods($param = array()) {
        $this->db->select('g.goods_id,g.add_time,g.shop_price,g.goods_sn,c.cate_name,gs.color');
        $this->db->from('goods_sku AS gs');
        $this->db->join('goods as g', 'gs.goods_id = g.goods_id', 'left');
        $this->db->join('category as c', 'g.cat_id = c.cate_id', 'left');
        
        if ($param['web_id']) {
             $this->db->join('shopify_goods AS sg', 'g.goods_id = sg.goods_id', 'left');
             $this->db->where("sg.web_id = '{$param['web_id']}' AND sg.is_sales = 1");
        }
        $this->db->group_by(array('gs.goods_id','gs.color'));
        
        $this->db->order_by('g.goods_id ASC');
    
        $query = $this->db->get();
        
        $_list = $query->result_array();
        
        return $_list;
    }

    public function developer_goods_sale($param = array()) {
        //admin
        if(!empty($param['admin_id'])){
            $this->db->where(['admin_id'=>$param['admin_id']]);
        }

        $admin = $this->db->from('admin')->where(['group'=>1,'is_del'=>0])->select('admin_id,admin_name')->get()->result_array();
        foreach ($admin as $key => $value) {
            $goods_web_count = $this->db->from('goods')->where(['admin_id'=>$value['admin_id']])->get()->result_array();
            $admin[$key]['goods_web_count'] = count($goods_web_count);
            $siteweb = $this->db->from('siteweb')->where(['is_delete'=>0])->select('web_name,web_id')->get()->result_array();
            foreach ($siteweb as $k => $val) {
                $shopify_goods = $this->db->from('shopify_goods as sg')
                            ->join('goods as g', 'sg.goods_id = g.goods_id', 'left')
                            ->where(['sg.web_id'=>$val['web_id'],'g.admin_id'=>$value['admin_id']])
                            ->select('sg.goods_id')->get()->result_array();
                $admin[$key]['web'][$k]['web_name'] = $val['web_name'].':'.count($shopify_goods);
            }
            $order = $this->db->from('order_goods as og')
                            ->join('goods as g', 'og.goods_id = g.goods_id', 'left')
                            ->where(['g.admin_id'=>$value['admin_id']])
                            ->select('og.goods_id,og.goods_price')->get()->result_array();
            $admin[$key]['goods_count'] = count($order);
            $admin[$key]['goods_price'] = array_sum(array_column($order,'goods_price'));

            $goods_group = $this->db->from('order_goods as og')
                    ->join('goods as g', 'og.goods_id = g.goods_id', 'left')
                    ->where(['g.admin_id'=>$value['admin_id']])
                    ->select('og.goods_id')
                    ->group_by('og.goods_id')
                    ->get()->result_array();
            if(count($goods_web_count) != 0){
                $sum = count($goods_group) / count($goods_web_count) * 100;
                $admin[$key]['goods_group'] = count($goods_group) .'/'. count($goods_web_count) .'='. $sum;
            }else{
                $admin[$key]['goods_group'] = 0;
            }
        }
        return $admin;
    }

    public function goods_list($param = array(), $is_all = 0,$excel_psge = 0) {
        if ($param['cate_name'] > 0) {
            $cat_id = $this->cat_res_id($param['cate_name']);
            //$cat_id = implode(',',$cat_id); 
        }

        /** @var user $user_lib */
        $user_lib = get_lib('user');
        $user_info = $user_lib->get_login_user_info();

        $a = '';
        $this->db->select('g.purchase_id,g.fabric_id,g.channel_id,g.tags,g.is_tort,g.is_testing,g.goods_id,g.goods_name,g.supp_url,g.supp_sn,g.is_delete,g.is_on_sale,g.add_time,g.updated_time,g.cn_name,g.original_img,g.in_price,g.shop_price,g.goods_weight,g.goods_sn,c.cate_name, s.suppliers_name');
        $this->db->from('goods AS g');
        $this->db->join('category AS c', 'g.cat_id = c.cate_id', 'left');
        $this->db->join('suppliers AS s', 's.suppliers_id = g.suppliers_id', 'left');
        $this->db->where('g.is_delete', 0);
        if($param['type_style']){
            $this->db->where('g.type_style', $param['type_style']);
        }

        if($user_info['style_type']){
            $this->db->where_in('g.style_type', $user_info['style_type']);
        }

        if ($param['goods_name']) {
            $param['goods_name'] =  trim($param['goods_name']);
            $this->db->where("(g.goods_name like '%{$param['goods_name']}%' OR g.goods_sn like '%{$param['goods_name']}%' OR g.supp_sn like '%{$param['goods_name']}%' OR g.`goods_id` = '{$param['goods_name']}' )");
//            $this->db->or_where(['g.goods_id'=>$param['goods_name']]);
        }

        if ($param['cate_name'] > 0) {
            $this->db->where_in('g.cat_id', $cat_id);
            //$this->db->where('g.cat_id = ' . $param['cate_name']);
        }

        if ($param['is_supp'] > 0) {
            $this->db->where("(g.suppliers_id = 0 OR g.in_price <= 0 OR g.supp_url = '')");
        }

        if($param['is_on_sales'] == 1){
            $this->db->where('(g.is_on_sale = 1  or g.is_on_sale = 2)');
        }elseif($param['is_on_sales'] == 2){
            $this->db->where('(g.is_on_sale = 0  or g.is_on_sale = 2)');
        }else{
            $this->db->where('(g.is_on_sale = 1 or g.is_on_sale = 2)');
        }

        if ($param['siteweb'] > 0 && $param['is_on_sale'] > 0) {
            if ($param['is_on_sale'] == 1) {
                $this->db->where(" g.goods_id in (select sg.goods_id from pcs_shopify_goods as sg where sg.web_id = '{$param['siteweb']}')");
            } else {
                $this->db->where("g.goods_id not in (select sg.goods_id from pcs_shopify_goods as sg where sg.web_id = '{$param['siteweb']}')");
            }
        }

        if($param['is_tort'] == 1){
            $this->db->where('g.is_tort = ' . 1);
        }elseif($param['is_tort'] == 2){
            $this->db->where('g.is_tort = ' . 0);
        }
        if ($param['channel_id'] > 0) {
            $this->db->where("g.channel_id = '{$param['channel_id']}'");
        }

        if ($param['admin_id'] > 0) {
            $this->db->where("g.admin_id = '{$param['admin_id']}'");
        }

        if ($param['add_time_start'] && $param['add_time_end']) {

            $param['add_time_start'] = strtotime($param['add_time_start']);
            $param['add_time_end'] = strtotime($param['add_time_end']);

            $this->db->where("g.add_time >= '{$param['add_time_start']}' and g.add_time <= '{$param['add_time_end']}'");
        }

        if ($is_all == 0) {
            $this->db->limit($this->limit_rows,$this->limit_rows * $param['page']);
        }

        //Eexcel分页
        if ($is_all == 99) {
            $this->db->limit(200,200*($excel_psge-1));
        }

        $this->db->order_by(' g.add_time DESC');
    
        $query = $this->db->get();
       // print_r($this->db->last_query());

        $_goods_list = $query->result_array();
        
        if ($_COOKIE['export_goods']) {
            $export_goods = array();
            if ($_COOKIE['export_goods']) {
                $_export_goods = explode(',', $_COOKIE['export_goods']);
                foreach ($_export_goods as $val) {
                    $export_goods[$val] = 1;
                }
            }
        }
    
        foreach ($_goods_list as $k => $row) {

            $this->db->select('SUM(od.goods_number) as goods_number,on.web_id')
                ->from('order_goods as od')
                ->join('order_info as on', 'od.order_id = on.order_id', 'left')
                ->where('od.goods_id = ' . $row['goods_id'])->group_by('on.web_id');


            if ($param['sale_time_start']) {
                $this->db->where("on.add_time >= " . strtotime($param['sale_time_start']));
            }

            if ($param['sale_time_end']) {
                $this->db->where("on.add_time <= " . strtotime($param['sale_time_start']));
            }

            $query = $this->db->get();

            $cc = $query->result_array();

            $_goods_list[$k]['cou'] = $cc;

            if ($export_goods[$row['goods_id']]) {
                $_goods_list[$k]['export_goods'] = 1;
            }


            $w_query = $this->db->select('on.web_id,on.web_name, sg.add_time')->from('shopify_goods as sg')->join('siteweb as on', 'sg.web_id = on.web_id')->where('sg.goods_id = ' . $row['goods_id'])->get();
            $_goods_list[$k]['wou'] = $w_query->result_array();

            $goods_sku = $this->db->from('goods_sku')->where(['goods_id'=>$row['goods_id'],'e_update'=>0,'is_delete'=>0])->get()->row_array();
            if($goods_sku){
                $_goods_list[$k]['goods_e_sku'] = 1;
            }
            $goods_sku = $this->db->from('goods_sku')->where(['goods_id'=>$row['goods_id'],'e_update'=>2,'is_delete'=>0])->get()->row_array();
            if($goods_sku){
                $_goods_list[$k]['goods_e_sku_img'] = 2;
            }
        }

        
        return $_goods_list;
    }

    public function ly_goods_list($offset = 0, $limit_rows = 15) {
        $this->db->select('g.*,s.suppliers_name');
        $this->db->from('ly_goods AS g');
        $this->db->join('suppliers AS s', 's.suppliers_id = g.suppliers_id', 'left');
        $this->db->where('g.is_delete', 0);
        $this->db->limit($limit_rows,$offset);
        $this->db->order_by('g.goods_id DESC');

        $query = $this->db->get();

        return $query->result_array();
    }

        //递归查询子类 返回ID
    /*public function category($array, $pid =0,&$list = []){
        foreach ($array as $key => $value){
            //第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
            if ($value['pid'] == $pid){
                //把数组放到list中
                $list[] = $value['cate_id'];
                //把这个节点从数组中移除,减少后续递归消耗
                unset($array[$key]);
                //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
                $this->category($array, $value['cate_id'],$list);
            }
        }
        return $list;
    }*/

public function cat_res_id($cat_id){
        $query = $this->db->from('category')->get();
        $arr = $query->result_array();
        foreach ($arr as $key => $value) {
            if($value['pid'] == $cat_id){
                $id[] = $value['cate_id'];
            }
        }
        if(empty($id)){
            $id[] = $cat_id;
        }
        foreach ($id as $k => $v) {
            foreach ($arr as $key => $value) {
                if($v == $value['pid']){
                    $id[] = $value['cate_id'];
                }
            }
        }
        $id[] = $cat_id;
        return $id;
    }


    public function goods_num($param)
    {
        if ($param['cate_name'] > 0) {
            $cat_id = $this->cat_res_id($param['cate_name']);
            //$cat_id = implode(',',$cat_id); 
        }

        /** @var user $user_lib */
        $user_lib = get_lib('user');
        $user_info = $user_lib->get_login_user_info();

        $a = '';
        $this->db->select('g.purchase_id,g.fabric_id,g.channel_id,g.tags,g.is_tort,g.is_testing,g.goods_id,g.goods_name,g.supp_url,g.supp_sn,g.is_delete,g.is_on_sale,g.add_time,g.updated_time,g.cn_name,g.original_img,g.in_price,g.shop_price,g.goods_weight,g.goods_sn,c.cate_name, s.suppliers_name');
        $this->db->from('goods AS g');
        $this->db->join('category AS c', 'g.cat_id = c.cate_id', 'left');
        $this->db->join('suppliers AS s', 's.suppliers_id = g.suppliers_id', 'left');
        $this->db->where('g.is_delete', 0);


        if($user_info['style_type']){
            $this->db->where_in('g.style_type', $user_info['style_type']);
        }

        if ($param['goods_name']) {
            $param['goods_name'] =  trim($param['goods_name']);
            $this->db->where("(g.goods_name like '%{$param['goods_name']}%' OR g.goods_sn like '%{$param['goods_name']}%' OR g.supp_sn like '%{$param['goods_name']}%' OR g.`goods_id` = '{$param['goods_name']}' )");
//            $this->db->or_where(['g.goods_id'=>$param['goods_name']]);
        }

        if ($param['cate_name'] > 0) {
            $this->db->where_in('g.cat_id', $cat_id);
            //$this->db->where('g.cat_id = ' . $param['cate_name']);
        }

        if ($param['is_supp'] > 0) {
            $this->db->where("(g.suppliers_id = 0 OR g.in_price <= 0 OR g.supp_url = '')");
        }

        if($param['is_on_sales'] == 1){
            $this->db->where('(g.is_on_sale = 1  or g.is_on_sale = 2)');
        }elseif($param['is_on_sales'] == 2){
            $this->db->where('(g.is_on_sale = 0  or g.is_on_sale = 2)');
        }else{
            $this->db->where('(g.is_on_sale = 1 or g.is_on_sale = 2)');
        }

        if ($param['siteweb'] > 0 && $param['is_on_sale'] > 0) {
            if ($param['is_on_sale'] == 1) {
                $this->db->where(" g.goods_id in (select sg.goods_id from pcs_shopify_goods as sg where sg.web_id = '{$param['siteweb']}')");
            } else {
                $this->db->where("g.goods_id not in (select sg.goods_id from pcs_shopify_goods as sg where sg.web_id = '{$param['siteweb']}')");
            }
        }

        if($param['is_tort'] == 1){
            $this->db->where('g.is_tort = ' . 1);
        }elseif($param['is_tort'] == 2){
            $this->db->where('g.is_tort = ' . 0);
        }
        if ($param['channel_id'] > 0) {
            $this->db->where("g.channel_id = '{$param['channel_id']}'");
        }

        if ($param['admin_id'] > 0) {
            $this->db->where("g.admin_id = '{$param['admin_id']}'");
        }

        if ($param['add_time_start'] && $param['add_time_end']) {

            $param['add_time_start'] = strtotime($param['add_time_start']);
            $param['add_time_end'] = strtotime($param['add_time_end']);

            $this->db->where("g.add_time >= '{$param['add_time_start']}' and g.add_time <= '{$param['add_time_end']}'");
        }
        
        // /** @var user $user_lib */
        // $user_lib = get_lib('user');
        // $user_info = $user_lib->get_login_user_info();


        // if ($param['cate_name'] > 0) {
        //     $cat_id = $this->cat_res_id($param['cate_name']);
        //     //$cat_id = implode(',',$cat_id); 
        // }

        // $this->db->from('goods as g');
        // $this->db->where('g.is_delete', 0);

        // if ($param['goods_name']) {
        //     $this->db->where("(g.goods_name like '%{$param['goods_name']}%' OR g.goods_sn like '%{$param['goods_name']}%')");
        // }

        // if ($param['cate_name'] > 0) {
        //     $this->db->where_in('g.cat_id', $cat_id);
        //     //$this->db->where('g.cat_id = ' . $param['cate_name']);
        // }

        // if($user_info['style_type']){
        //     $this->db->where_in('g.style_type', $user_info['style_type']);
        // }

        // if($param['is_tort'] == 1){
        //     $this->db->where('g.is_tort = ' . 1);
        // }elseif($param['is_tort'] == 2){
        //     $this->db->where('g.is_tort = ' . 0);
        // }

        // if ($param['order_sorting']) {
        //     if ($param['siteweb']) {
        //         $a = " AND web_id = '{$param['siteweb']}'";
        //     }

        //     $order_by = "(SELECT SUM(og.goods_number) FROM pcs_order_goods AS og LEFT JOIN pcs_order_info AS oi ON og.order_id = oi.order_id WHERE og.goods_id = g.goods_id {$a}) {$param['order_sorting']}, ";
        // }

        // if ($param['siteweb'] > 0 && $param['is_on_sale'] > 0) {
        //     $this->db->join('shopify_goods as sg', 'sg.goods_id = g.goods_id', 'left');
        //     if ($param['is_on_sale'] == 1) {
        //         $this->db->where("sg.web_id = '{$param['siteweb']}'");
        //     } else {
        //         $this->db->where("sg.web_id != '{$param['siteweb']}'");
        //     }

        // }

        // if($param['is_on_sales'] == 1){
        //     $this->db->where('g.is_on_sale = ' . 1);
        // }elseif($param['is_on_sales'] == 2){
        //     $this->db->where('g.is_on_sale = ' . 0);
        // }
        // if ($param['channel_id'] > 0) {
        //     $this->db->where("g.channel_id = '{$param['channel_id']}'");
        // }
        // if ($param['admin_id'] > 0) {
        //     $this->db->where("g.admin_id = '{$param['admin_id']}'");
        // }

        // if ($param['add_time_start'] && $param['add_time_end']) {

        //     $param['add_time_start'] = strtotime($param['add_time_start']);
        //     $param['add_time_end'] = strtotime($param['add_time_end']);

        //     $this->db->where("g.add_time >= '{$param['add_time_start']}' and g.add_time <= '{$param['add_time_end']}'");
        // }
        return $this->db->count_all_results();
    }
    
    public function goods_supp_info($goods_id) {
        $query = $this->db->from('goods_supp')->where(array('goods_id' => $goods_id, 'is_host' => 1))->get();
        return $query->row_array();
    }

    public function goods_info($goods_id, $is_all = 0, $if_del = 0)
    {
        $query = $this->db->from('goods')->where(array('goods_id' => $goods_id))->get();

        $goods = $query->row_array();

        if ($is_all == 1 && $goods) {
        	//sku
            $goods['sku'] = $this->get_goods_sku($goods_id, $if_del);

        	//images
			$img_query = $this->db->from('goods_album')->where("goods_id = '$goods_id' and is_delete = 0")->order_by('album_sort ASC')->get();
			$images = $img_query->result_array();
			$goods['images'] = array();
			foreach ($images as $img) {
				$goods['images'][$img['album_id']] = $img;
			}
			
			//supp
            $supp_query = $this->db->from('goods_supp')->where("goods_id = '{$goods_id}'")->get();
			$goods_supp = $supp_query->result_array();
			foreach ($goods_supp as $supp) {
			    $goods['supp'][$supp['supp_id']] = $supp;
            }
		}


        return $goods;
    }
    
    public function get_goods_sku($goods_id, $if_del = 0)
    {
        $where_arr = array(
            'goods_id' => $goods_id
        );

        if ($if_del == 1) {
            $where_arr['is_delete'] = 0;
            $where_arr['is_on_sale'] = 1;
        }

        $sku_query = $this->db->from('goods_sku')->where($where_arr)->order_by("FIELD(size, 'S','M','L','XL','XXL','3XL','4XL','5XL','6XL','7XL','8XL','OneSize'),sort asc")->get();
        $_sku = $sku_query->result_array();
        
        $sku = array();
        foreach ($_sku as $sku_row) {
            $sku[$sku_row['sku_num_sn']] = $sku_row;
        }
        
        
        return $sku;
    }
    public function goods_color($goods_id){
        $where_arr = array(
            'goods_id' => $goods_id,
            'is_delete' => 0,
            'is_on_sale' => 1
        );

        $res = $this->db->from('goods_sku')->select('color,sort')->where($where_arr)->order_by('sort asc')->group_by('color')->get()->result_array();
        return $res;
    }

    public function goods_sale_info($goods_id, $end = '', $st = '')
    {
        $shopify_query = $this->db->select('i.web_id,s.web_name,i.goods_id')->from('shopify_goods as i')->join('siteweb as s', 'i.web_id = s.web_id', 'left')->where('goods_id', $goods_id)->get();

        if (!$end) {
            $end = date('Y-m-d', time());
        }

        if (!$st) {
            $st = date('Y-m-d', time() - (7 * 24 * 60 * 60));
        }

        $time = $this->getSchemeDate($st, $end);

        $shopify_goods = $shopify_query->result_array();

        $q =array();
        foreach ($time as $row1) {
            foreach ($shopify_goods as $row) {
                $shopify_q = $this->db->select('count(1) as c')->from('order_goods as b')->join('order_info as oi', 'b.order_id = oi.order_id', 'left')->where("b.goods_id = {$goods_id} and oi.web_id = {$row['web_id']} and oi.add_time >= {$row1['begin_date']} and oi.add_time <= {$row1['end_date']}")->get();
                $q[date('Y-m-d', $row1['begin_date'])][$row['web_id']] = $shopify_q->row_array();
            }
        }

        return array(
            's' => $shopify_goods,
            'q' => $q
        );
    }

    function getSchemeDate($begin_date = '', $end_date = '')
    {
        if (!$begin_date || !$end_date) return false;
        $diff_time = strtotime($end_date) + 24 * 60 * 60 - strtotime($begin_date);
        $diff_week = round($diff_time / (1 * 24 * 60 * 60));

        $times_arr = array();
        foreach (range(1, $diff_week) as $item) {
            $times_arr[$item]['end_date'] = strtotime($begin_date)  + ($item * 24 * 60 * 60);
            $times_arr[$item]['begin_date'] = $times_arr[$item]['end_date'] - (1 * 24 * 60 * 60);

        }
        return $times_arr;

    }

    public function insert_shopify_goods($row = array())
    {

        if (!$row['cate_id']) {
            $_cate = array(
                'cate_name' => strval($row['product_type']),
                'shopify_id' => $row['id'],
                'add_time' => time()
            );
            $this->db->insert('category', $_cate);
            $row['cate_id'] = $this->db->insert_id();
        }

        $_goods = array(
            'goods_name' => $row['title'],
            'cn_name' => '',
            'goods_sn' => $row['goods_sn'],
            'cat_id' => $row['cate_id'],
            'goods_weight' => 0.00,
            'in_price' => 0.00,
            'shop_price' => $row['variants'][0]['price'],
            'market_price' => $row['variants'][0]['price'],
            'suppliers_id' => 0,
            'supp_url' => '',
            'original_img' => $row['image']['src'],
            'shopify_id' => $row['id'],
            'body_html' => $row['body_html'],
            'tags' => $row['tags'],
            'add_time' => strtotime($row['created_at']),
            'updated_time' => strtotime($row['updated_at'])
        );

        $query = $this->db->insert('goods', $_goods);
        $goods_id = $this->db->insert_id();

        if ($goods_id) {

            if ($row['variants']) {
                $_goods_sku = array();
                foreach ($row['variants'] as $v) {

                    $color = strtr($v['option2'], array(' ' => ''));

                    $_goods_sku[] = array(
                        'sku_sn' => "{$goods_id}-{$color}-{$v['option1']}",
                        'sku_num_sn' => strval(preg_replace('/[a-zA-Z]+/', '', $v['sku'])),
                        'goods_id' => $goods_id,
                        'color' => strval($v['option2']),
                        'size' => strval($v['option1']),
                        'inventory_policy' => $v['inventory_policy'] == 'deny' ? 0 : 1,
                        'sku_number' => 0,
                        'shop_price' => $v['price'],
                        'is_delete' => 0,
                        'update_time' => strtotime($v['updated_at']),
                        'add_time' => strtotime($v['created_at']),
                        'shopify_id' => $v['id']
                    );
                }
                print_r($_goods_sku);
                $this->db->insert_batch('goods_sku', $_goods_sku);
            }

            if ($row['images']) {
                $_images = array();
                foreach ($row['images'] as $image) {
                    $_images[] = array(
                        'goods_id' => $goods_id,
                        'sku_id' => 0,
                        'original_img' => $image['src'],
                        'width' => $image['width'],
                        'height' => $image['height'],
                        'is_delete' => 0,
                        'add_time' => strtotime($image['created_at'])
                    );
                }
                $this->db->insert_batch('goods_album', $_images);
            }

        }

        return $goods_id;
    }

    //侵权 修改
    public function goodds_tort($id = 0){
        //查询商品状态
        $this->db->select('is_tort');
        $this->db->from('goods');
        $this->db->where('goods_id', $id);
        $arr = $this->db->get();    
        $arr = $arr->row_array();
        if($arr['is_tort'] == 0){
            $result = '侵权';
            $where['is_tort'] = 1;
        }else{
            $result = '不侵权';
            $where['is_tort'] = 0;
        }
        //修改侵权状态
        $this->db->where('goods_id', $id);
        $res = $this->db->update('goods', $where);
        if($res !== false){
            return $result;
        }
    }

    public function insert_goods($row = array(), $id = 0)
    {
        $time = time();

        $_goods = array(
            'goods_name' => $row['goods_name'],
            'cn_name' => $row['cn_name'],
            'goods_sn' => $row['goods_sn'],
            'cat_id' => $row['cat_id'],
            'goods_weight' => $row['goods_weight'],
            'in_price' => $row['in_price'],
            'shop_price' => $row['shop_price'],
            'market_price' => $row['market_price'],
            'suppliers_id' => $row['suppliers_id'],
            'compare_at_price' => $row['compare_at_price'],
            'supp_url' => $row['supp_url'],
            'supp_sn' => $row['supp_sn'],
            'style_type' => $row['style_type'] ? : 1,
            'body_html' => $row['body_html'],
            'is_testing' => $row['is_testing'],
            'goods_attr' => $row['goods_attr'],
            'type_id' => $row['type_id'],
            'tags' => $row['tags'],
            'updated_time' => $time,
            'channel_id' => $row['channel_id'],
            'sale_status' => $row['sale_status']//销售状态
        );
        
        if ($row['images'][0]['file_name']) {
            $_goods['original_img'] = $row['images'][0]['file_name'];
        }
        
        $goods_id = $id;
        if ($id) {
            $this->db->where('goods_id', $id);
            $this->db->update('goods', $_goods);
        } else {
            
            $_goods['add_time'] = $time;
            $_goods['admin_id'] = intval($row['admin_id']);
            
            $this->db->insert('goods', $_goods);
            $goods_id = $this->db->insert_id();
        }

        if ($goods_id) {
            
            //供应商链接
            $_supp = $row['supp'];
            $_supp['goods_id'] = $goods_id;
    
            $this->db->where('goods_id', $goods_id);
            $this->db->update('goods_supp', array('is_host' => 0));
            
            if ($_supp['g_supp_id']) {
                $this->db->where('g_supp_id', $_supp['g_supp_id']);
                $this->db->update('goods_supp', $_supp);
            } else {
                $_supp['add_time'] = $time;
                $this->db->insert('goods_supp', $_supp);
            }


            if ($row['sku']) {
                $_goods_sku = array();
                $ml = preg_replace("/[0-9]/","",$row['goods_sn']);
                foreach ($row['sku'] as $row_key => $v) {
    
                    $size = trim($v['size']);
                    $color = trim($v['color']);
                    $number = intval($v['number']);

                    $default_update_data = array();

                    if(is_numeric($row['pro_imgs'][$row_key])){//赋值所提交的img路径信息
                        $sku_img_num = $row['pro_imgs'][$row_key];
                        $default_update_data['album_url'] = $row['images_key'][$sku_img_num]['file_name'];

                        $sku_row_data = $this->db->from('goods_sku')->where('sku_id', $v['sku_id'])->get()->row_array();
                        if($sku_row_data['e_update'] != 0){
                            $default_update_data['e_update'] = 2; //标记改图片为修改过
                        }

                    }
                   
                    switch ($v['handle']) {
                        case 'insert':

                            $insert_data = array(
                                'sku_sn' => $ml == 'ML' ? "{$goods_id}-{$v['sku_sn']}" : "{$v['sku_sn']}",
                                'sku_num_sn' => strval($v['sku_num_sn']),
                                'goods_id' => $goods_id,
                                'color' => $color,
                                'size' => $size,
                                'inventory_policy' => 0,
                                'sku_number' => $number,
                                'shop_price' => $row['shop_price'],
                                'is_delete' => 0,
                                'update_time' => $time,
                                'add_time' => $time,
                                'shopify_id' => 0,
                                'ali_color' => $v['ali_color'],
                                'ali_size' => $v['ali_size']
                            );

                            if($v['album_url']){
                                $insert_data['album_url'] = $v['album_url'];
                            }
                            $_goods_sku['insert'][] = array_merge($insert_data, $default_update_data);
                            break;
                        case 'update':
                            $update_data = array(
                            	'sku_id' => $v['sku_id'],
                                
                                'ali_color' => $v['ali_color'],
                                'ali_size' => $v['ali_size'],
                                'is_delete' => 0
                            );

                            $_goods_sku['update'][] = array_merge($update_data, $default_update_data);
                            break;
                        case 'delete':
                            $_goods_sku['update'][] = array(
                                'sku_id' => $v['sku_id'],
                                'is_delete' => 1
                            );
                            break;
                    }
                    
                }

                if ($_goods_sku['insert']) {
                    $this->db->insert_batch('goods_sku', $_goods_sku['insert']);
                }
                if ($_goods_sku['update']) {
                    $this->db->update_batch('goods_sku', $_goods_sku['update'], 'sku_id');
                }
            }

            if ($row['images']) {
                $_images = array();
                foreach ($row['images'] as $k => $image) {
                    
                    switch ($image['handle']) {
                        case 'update':
                            $_images['update'][] = array(
                                'album_sort' => $k,
                                'album_id' => $image['album_id']
                            );
                            break;
                        case 'insert':
                            $_images['insert'][] = array(
                                'goods_id' => $goods_id,
                                'sku_id' => 0,
                                'original_img' => $image['file_name'],
                                'big_img' => '',
                                'small_img' => '',
                                'width' => $image['image_width'],
                                'height' => $image['image_height'],
                                'album_sort' => $k,
                                'is_delete' => 0,
                                'add_time' => $time
                            );
                            break;
                        case 'delete':
                            $_images['update'][] = array(
                                'album_id' => $image['album_id'],
                                'is_delete' => 1
                            );
                            break;
                    }
                }
                
                if ($_images['insert']) {
                    $this->db->insert_batch('goods_album', $_images['insert']);
                }
                if ($_images['update']) {
                    $this->db->update_batch('goods_album', $_images['update'], 'album_id');
                }
            }

        }
        
        return $goods_id;
    }

    public function update_goods($goods_id, $data = array())
	{

	    $this->db->where('goods_id', $goods_id);

        if (isset($data['is_on_sale'])) {
            $this->db->set('is_on_sale', $data['is_on_sale']);
            $this->db->set('reason',$data['reason']);
            $this->db->set('on_sale_time', time());
        }
        if(isset($data['reason'])){
            $this->db->set('reason',$data['reason']);
        }

        $this->db->update('goods');
	}


    function build_goods_sn($goods_id = 0,$sn_fix = '', $number = 0)
    {


        if (!$goods_id) {
            $this->db->select_max('goods_id', 'goods_id');
            $query = $this->db->get('goods');
            $goods = $query->row_array();
            $goods_id = $goods['goods_id'];
        }

        $sn_prefix		=	$sn_fix ? $sn_fix : 'ML';
        $goods_id		=	intval($goods_id) + (mt_rand(1700, 4000) . 888) + mt_rand(10, 99) + $number;
        $goods_sn = $sn_prefix . $goods_id;

        $this->db->from('goods');
        $this->db->where('goods_sn', $goods_sn);
        $query = $this->db->get();
        $sn = $query->row_array();

        if ($sn)
        {
            $new_sn = $goods_id + mt_rand(1, 2);
            $goods_sn = $sn_prefix . $new_sn;
        }
        return $goods_sn;
    }

    public function get_image_path_cdn($image='')
    {
        // $arr = explode('|',$GLOBALS['_CFG']['cloud_img']);
        $str = "https://img1.lovelywholesale.com/|https://img3.lovelywholesale.com/|https://img5.lovelywholesale.com/|https://img6.lovelywholesale.com/|https://img7.lovelywholesale.com/";
        $arr = explode('|',$str);
        $key = array_rand($arr);
        $url = $arr[$key].$image;
        return $url;
    }


    /**
     *
     * 产品上下架
     *
    */

    public function is_on_sale($data)
    {

        $time = time();

        //产品上下架
        $goods_data = array(
            'is_on_sale' => $data['is_on_sale'],
            'reason' => $data['reason'],
            'on_sale_time' => $time
        );
        $this->db->where('goods_id', $data['goods_id']);
        $this->db->update('goods', $goods_data);

        //SKU上下架
        $sku_data = array(
            'is_on_sale' => $data['on_sale'],
            'reason' => $data['reason'],
            'on_sale_time' => $time
        );
        $this->db->where_in('sku_id', $data['sku_ids']);
        $this->db->update('goods_sku', $sku_data);


        //站点上下架
        $sku_data = array(
            'is_sales' => $data['on_sale'],
            'on_sale_time' => $time
        );
        $this->db->where('goods_id',$data['goods_id']);

        if(!empty($data['web_ids'])){
            $this->db->where_in('web_id', $data['web_ids']);
        }
        $this->db->update('shopify_goods', $sku_data);

        //日志
        $log_data = array(
            'goods_id' => $data['goods_id'],
            'sku_ids' => ',' . implode(',', $data['sku_ids']) . ',',
            'web_ids' => ',' . implode(',', $data['web_ids']) . ',',
            'reason' => $data['reason'],
            'is_on_sale' => $data['is_on_sale']
        );
        $this->shelf_log($log_data);
    }

    //上下架SKU操作日志
    public function shelf_log($arr){

        $_arr = array(
            'goods_id' => $arr['goods_id'],
            'sku_ids' => $arr['sku_ids'],
            'web_ids' => $arr['web_ids'],
            'admin_id' => intval($_SESSION['admin_id']),
            'reason' => intval($arr['reason']),
            'is_on_sale' => $arr['is_on_sale'],
            'add_time' => time()
        );

        $this->db->insert('on_sale_log', $_arr);
    }

    public function up_goods_supp_info($data)
    {
        $time = time();


        $data_url = array(
            'goods_id' => $data['goods_id'],
            'supp_id' => $data['supp_id'],
            'in_price' => $data['in_price'],
            'is_host' => $data['is_host'],
            'supp_url' => $data['supp_url'],
            'add_time' => $time
        );

        $data_url = array_filter($data_url);

        $goods_supp = array();
        if ($data['is_host'] == 1) {
            $query = $this->db->from('goods_supp')->where("goods_id = '{$data['goods_id']}' AND is_host = 1")->get();
            $goods_supp = $query->row_array();
        }

        if ($goods_supp) {
            $g_supp_id = $goods_supp['g_supp_id'];
            $this->db->update('goods_supp', $data_url, array('g_supp_id' => $g_supp_id));
        } else {
            $this->db->insert('goods_supp', $data_url);
            $g_supp_id = $this->db->insert_id();
        }



        if ($data['is_host'] == 1) {

            $data_goods = array(
                'g_supp_id' => $g_supp_id,
                'suppliers_id' => $data['supp_id'],
                'type_id' => $data['type_id'],
                'in_price' => $data['in_price'],
                'supp_url' => $data['supp_url']
            );

            $data_goods = array_filter($data_goods);
            $this->db->update('goods', $data_goods, array('goods_id' => $data['goods_id']));
        }

    }

    public function get_type_id($type_name) {
       $query = $this->db->from('goods_type')->where("cat_name_zh = '{$type_name}'")->get();

       $type = $query->row_array();

       return $type['cat_id'];
    }

    public function goods_up_shopify_list($goods_ids)
    {
        $query = $this->db->from('goods')->where("goods_id in ({$goods_ids})")->get();

        $goods = $query->result_array();

        return $goods;
    }

    public function siteweb_goods($goods_sn = array()) {
        $query = $this->db->from('goods')->where_in('goods_sn', $goods_sn)->get();

        $goods = $query->result_array();

        $goods_ids = array_column($goods, 'goods_id');

        $_sku_query = $this->db->from('goods_sku')->where_in('goods_id', $goods_ids)->get();
        $_sku = $_sku_query->result_array();
        $sku = array();
        foreach ($_sku as $item) {
            $sku[$item['goods_id']][$item['sku_id']] = $item;
        }

        $_img_query = $this->db->from('goods_album')->where_in('goods_id', $goods_ids)->get();
        $_img = $_img_query->result_array();
        $img = array();
        foreach ($_img as $item) {
            $img[$item['goods_id']][$item['album_id']] = $item;
        }

        return array(
            'goods' => $goods,
            'sku' => $sku,
            'img' => $img
        );

    }
}
